package com.softeem.sss.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import com.softeem.sss.dto.User;
import com.softeem.sss.utils.DBUtils;

/**
 * 用户数据访问对象
 * @author mrchai
 *
 */
public class UserDAO {

	/**
	 * 用户添加
	 * @param user
	 * @return
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	public boolean insert(User user) throws ClassNotFoundException, SQLException{
		String sql = "insert into tb_user(username,password) values(?,?)";
		return DBUtils.exeUpdate(sql, user.getUsername(),user.getPassword());
	}
	
	/**
	 * 根据用户名查询用户信息
	 * @param username
	 * @return
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	public User findByUsername(String username) throws ClassNotFoundException, SQLException{
		
		String sql = "select * from tb_user where username=? and isDel=0";
		//4.执行sql
		ResultSet rs = DBUtils.exeQuery(sql, username);
		User user = null;
		//5.处理结果
		if(rs.next()){
			int uid = rs.getInt("uid");
			String pwd = rs.getString("password");
			int intergral = rs.getInt("integral");
			Timestamp regTime = rs.getTimestamp("regtime");
			Timestamp lastLogin = rs.getTimestamp("lastlogin");
			int isDel = rs.getInt("isDel");		
			user = new User(uid, username, pwd, intergral, regTime, lastLogin, isDel);
		}
		//6.关闭资源
		DBUtils.close(rs, null,null);
		return user;
	}
	
	public User findByUid(int uid) throws ClassNotFoundException, SQLException{
		
		String sql = "select * from tb_user where uid=? and isDel=0";
		//4.执行sql
		ResultSet rs = DBUtils.exeQuery(sql, uid);
		User user = null;
		//5.处理结果
		if(rs.next()){
			String username = rs.getString("username");
			String pwd = rs.getString("password");
			int intergral = rs.getInt("integral");
			Timestamp regTime = rs.getTimestamp("regtime");
			Timestamp lastLogin = rs.getTimestamp("lastlogin");
			int isDel = rs.getInt("isDel");		
			user = new User(uid, username, pwd, intergral, regTime, lastLogin, isDel);
		}
		//6.关闭资源
		DBUtils.close(rs, null,null);
		return user;
	}
	
	/**
	 * 更新登录时间
	 * @param uid
	 * @return
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	public boolean updateLoginTime(int uid) throws ClassNotFoundException, SQLException{
		return DBUtils.exeUpdate("update tb_user set lastlogin=now() where uid=?", uid);
	}
	
	/**
	 * 修改用户积分
	 * @param user
	 * @return
	 */
	public boolean updateIntegral(User user){
		String sql = "update tb_user set integral=? where uid=?";
		return DBUtils.exeUpdate(sql, user.getIntergral(),user.getUid());
	}

	
}
